package com.pinda.controller.login;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pinda.common.CommonClass;
import com.pinda.dto.logindto.LoginBody;
import com.pinda.dto.returndto.R;
import com.pinda.entity.AuthUser;
import com.pinda.service.AuthUserService;
import com.pinda.utils.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    public RedisTemplate redisTemplate;

    @Autowired
    AuthUserService authUserService;




    @GetMapping("/codeImage")
    public R<Map> getCode(HttpServletResponse response) {

        //定义图形验证码的长和宽  码值个数  干扰圈数
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(90, 40, 4, 10);
        BufferedImage codeImg = circleCaptcha.getImage();

        String code = circleCaptcha.getCode();
        System.out.println("code = " + code);
        //生成唯一ID
        String uuid = IdUtil.simpleUUID();
        //存储验证码有效期为2分钟
        redisTemplate.opsForValue().set(CommonClass.VALIDATE_DATE + uuid, code, 2, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(codeImg, "jpg", os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, String> map = new HashMap<>();
        map.put("uuid", uuid);
        map.put("img", Base64.encode(os.toByteArray()));
        return R.success(map);
    }


    @PostMapping
    public R<Map> login(@RequestBody LoginBody loginBody) {
        if (ObjectUtil.isEmpty(loginBody) || StrUtil.isEmpty(loginBody.getUsername()) || StrUtil.isEmpty(loginBody.getPassword())) {
            return R.error("请重新账户或密码");
        }
        if (StrUtil.isEmpty(loginBody.getCode()) || StrUtil.isEmpty(loginBody.getUuid())) {
            return R.error("请重新获取验证码");
        }
        Object authCode = redisTemplate.opsForValue().get(CommonClass.VALIDATE_DATE + loginBody.getUuid());
        if (ObjectUtil.isEmpty(authCode) || !(authCode + "").equals(loginBody.getCode())) {
            return R.error("验证码输入错误");
        }
        AuthUser user = authUserService.getOne(Wrappers.lambdaQuery(AuthUser.class)
                .eq(AuthUser::getAccount, loginBody.getUsername())
                .eq(AuthUser::getPassword, loginBody.getPassword()));
        if (ObjectUtil.isEmpty(user)) {
            return R.error("账户或密码错误");
        }
        Map<String, Object> map = new HashMap<>();

        String token = JWT.create()
                .setPayload("id", user.getId())
                .setPayload("orgId",user.getOrgId())
                .setKey(CommonClass.TOKEN_KEY.getBytes())
                .sign();
        user.setPassword("");
        map.put("user", user);
        map.put(CommonClass.TOKEN,token);
        return R.success(map);
    }
}
